package com.qianji.petmall.ware.listener;

import com.qianji.common.to.mq.OrderTo;
import com.qianji.common.to.mq.StockLockedTo;
import com.qianji.petmall.ware.service.WareSkuService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author liang zai
 * @date 2022/5/13 14:27
 * @description
 */
@Component
@RabbitListener(queues = "stock.release.stock.queue")
public class StockReleaseListener {
    @Autowired
    WareSkuService wareSkuService;

    /**
     * 这个是监听死信消息
     * 1、库存自动解锁
     *  下订单成功，库存锁定成功，接下来的业务调用失败，导致订单回滚。之前锁定的库存就要自动解锁
     *
     *  2、订单失败
     *      库存锁定失败
     *
     *   只要解锁库存的消息失败，一定要告诉服务解锁失败
     */

    @RabbitHandler
    public void stockLockedRelease(StockLockedTo to, Message message, Channel channel) throws IOException {
        System.out.println("******收到解锁库存的延时信息******，准备解锁" + to.getTaskDetail().getId());
        try {
            //TODO 解锁库存
            wareSkuService.releaseLock(to);

            //手动ack删除消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }catch (Exception e){
            //解锁失败 需要重新放入队列中
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }

    }
    @RabbitHandler
    public void stockLockedRelease(OrderTo to, Message message, Channel channel) throws IOException {
        System.out.println("******订单关闭******，准备解锁" + to.getOrderSn());
        try {
            //TODO 解锁库存
            wareSkuService.releaseLock(to);

            //手动ack删除消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }catch (Exception e){
            //解锁失败 需要重新放入队列中
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }

    }
}
